const db = uniCloud.database();
const { guid } = require('../../common/utils');
const { curTimeStamp } = require('../../common/time');
const userInfo = require('../user/user-info');
const { groupCreate } = require('../group/index');
module.exports = async function(options = {}) {
	const { nickname, avatar, type } = options;
	const token = this.getUniIdToken();
	const user_info = await userInfo({ token });
	// 获取没有重复的id
	async function getCharacterId(character) {
		const characterId = guid(24);
		const findDataRes = await db.collection('a-dz-character-list').where({ characterId }).get({ getOne: true });
		if (findDataRes.data.length) {
			return getCharacterId();
		}
		return characterId;
	}
	if (user_info.code == 0) { //获取有效用户信息
		let { _id: uid, member_time, character = [] } = user_info.data;
		if (member_time <= 0 && character.length >= 2) {
			return {
				code: -1,
				msg: '升级会员，解锁更多限制'
			}
		} else if (member_time > 0 && character.length >= 5) {
			return {
				code: -1,
				msg: '最多创建5个角色'
			}
		}
		const characterId = await getCharacterId(character);
		const characterParams = {
			nickname,
			avatar,
			type,
			uid,
			characterId
		}
		character.unshift(characterId);
		const promiseParams = [
			db.collection('a-dz-character-list').add(characterParams),
			db.collection('uni-id-users').doc(uid).update({ character })
		]
		if (type === 'TEACHER') { //老师角色创建分组
			promiseParams.push(groupCreate({ characterId, uid, token }));
		}
		const [addCharacterRes] = await Promise.all(promiseParams);
		return {
			code: 0,
			data: characterParams,
			msg: '创建成功'
		}
	} else {
		return user_info;
	}
}